package com.beyondbit.demo.controller;

import com.alibaba.fastjson.JSONObject;
import com.beyondbit.demo.common.UUIDGenerator;
import com.beyondbit.demo.common.Util;
import com.beyondbit.demo.entity.CommonAttachment;
import com.beyondbit.demo.entity.EntityFileInfo;
import com.beyondbit.demo.entity.EntitySignatureLog;
import com.beyondbit.demo.entity.User;
import com.beyondbit.demo.service.CommonAttachmentService;
import com.beyondbit.demo.service.SwwSignatureService;
import com.beyondbit.demo.service.UserService;
import com.beyondbit.web.infrastructure.controller.BaseApiController;
import com.beyondbit.web.infrastructure.model.JsonResultMessage;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.SneakyThrows;
import lombok.var;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.ofdrw.converter.ConvertHelper;
import org.ofdrw.converter.FontLoader;
import org.ofdrw.converter.GeneralConvertException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.*;

/**
 * 商委签章接口
 *
 * @ProjectName: beyondbit-demo
 * @Package: com.beyondbit.demo.swwSignature.controller
 * @ClassName: SwwSignatureController
 * @Author: zq
 * @Description:
 * @Date: 2021/12/13 17:32
 * @Version: 1.0
 */
@CrossOrigin
@RestController
@RequestMapping("/swwSignature")
public class SwwSignatureController extends BaseApiController {

    //region   配置文件相关
    //签章url
    @Value("${signature.Apply_CA_URL}")
    private String Apply_CA_URL;

    //印章页面签署接口地址
    @Value("${signature.Apply_Seal_Address}")
    private String Apply_Seal_Address;

    //秘钥
    @Value("${signature.Apply_Secret}")
    private String Apply_Secret;

    //创建应用分配的token
    @Value("${signature.Apply_Token}")
    private String Apply_Token;

    //phone
    @Value("${signature.phone}")
    private String phone;

    //新区商委印章ID
    @Value("${signature.sealIds}")
    private String sealIds;

    //文件存储路径
    @Value("${info.profile}")
    private String profile;

    //保存表单
    @Value(value = "${fileRunTimeApi.REST_API_PROCFORMDESIGNDATA}")
    private String REST_API_PROCFORMDESIGNDATA;

    //启动流程
    @Value(value = "${fileRunTimeApi.REST_API_START}")
    private String REST_API_START;

    //FAWEN_FORM_ID
    @Value(value = "${fileRunTimeApi.FAWEN_FORM_ID}")
    private String FAWEN_FORM_ID;

    //FAWEN_FORM_TEMPLATE_ID
    @Value(value = "${fileRunTimeApi.FAWEN_FORM_TEMPLATE_ID}")
    private String FAWEN_FORM_TEMPLATE_ID;
    //endregion

    @Autowired
    private SwwSignatureService swwSignatureService;

    @Autowired
    private CommonAttachmentService commonAttachmentService;

    @Autowired
    private UserService userService;

    @RequestMapping("/testB")
    public JsonResultMessage testB() {
        Map<String, Object> resultParam = new HashMap<>();
        //response.setHeader("Access-Control-Allow-Origin", "*");
        UUIDGenerator uuid = new UUIDGenerator();
        /*EntitySignatureLog signatureLog = new EntitySignatureLog();
        signatureLog.setId(uuid.newId());
        signatureLog.setCommonId("D8F2E3FC-4101-47C4-B177-F55611130E7F");
        signatureLog.setDocumentId("2908564179862151647");
        signatureLog.setSignatrueUrl("http://10.85.250.37:9080/openview?viewToken=2465a1dd-75cc-4a04-aea3-796cba8b0c5a");
        signatureLog.setDateCreate(new Date());
        signatureLog.setRemark("{\"code\": \"0\",\"documentId\": \"2908564179862151647\",\"message\": \"SUCCESS\",\"url\": \"http://10.85.250.37:9080/openview?viewToken=2465a1dd-75cc-4a04-aea3-796cba8b0c5a\"}");

        int addSignLogNum = swwSignatureService.insterSignatureLog(signatureLog);
        resultParam.put("addSignLogNum", addSignLogNum);*/


        resultParam.put("documentId", "2908187261061029892");
        resultParam.put("message", "SUCCESS");
        resultParam.put("url", "http://10.85.250.37:9080/openview?viewToken=ffd06238-db73-4ad3-8cb8-47485d4e729e");


        String timestamp = Util.getTimeStamp();
        resultParam.put("x-qys-timestamp", timestamp);
        String signature = Apply_Token + "" + Apply_Secret + "" + timestamp;
        //System.out.println(signature);
        String xQysSignature = DigestUtils.md5DigestAsHex(signature.getBytes(StandardCharsets.UTF_8));
        //System.out.println(xQysSignature);
        resultParam.put("x-qys-signature", xQysSignature);
        resultParam.put("x-qys-accesstoken", Apply_Token);


        return success("签章成功", resultParam);
    }


    //region 查询签章状态

    /**
     * 查询签章状态
     *
     * @return
     * @Author sandy
     */
    @PostMapping("/getSignatureStatus")
    @ResponseBody
    public JsonResultMessage getSignatureStatus(@RequestBody Map<String, Object> data) {
        try {
            if (data.get("refTableId") == null) {
                throw new Exception("关系id未能获取");
            }

            String refTableId = data.get("refTableId").toString();


            //region 查询数据库，是否存在该签章
            var swwSignatureLog = swwSignatureService.selSignLogInfoByCommonId(refTableId);
            if (swwSignatureLog != null) {
                //如果没有下载最新签名后的文档，则下载
                if (swwSignatureLog.getSignatrueAttachmentId() == null || StringUtils.isEmpty(swwSignatureLog.getSignatrueAttachmentId())) {

                    //region 下载签名后的文档
                    String url = Apply_CA_URL + "document/download?documentId=" + swwSignatureLog.getDocumentId();

                    FileOutputStream fileOut = null;
                    HttpURLConnection conn = null;
                    InputStream inputStream = null;


                    //时间戳
                    String xQysTimestamp = Util.getTimeStamp();
                    //MD5加密前签名
                    String signature = Apply_Token + "" + Apply_Secret + "" + xQysTimestamp;
                    //System.out.println(signature);
                    //MD5加密后签名
                    String xQysSignature = DigestUtils.md5DigestAsHex(signature.getBytes(StandardCharsets.UTF_8));
                    //System.out.println(xQysSignature);


                    try {
                        //region 获得下载流
                        // 建立链接
                        URL httpUrl = new URL(url);
                        conn = (HttpURLConnection) httpUrl.openConnection();

                        conn.setRequestProperty("x-qys-timestamp", xQysTimestamp);
                        conn.setRequestProperty("x-qys-signature", xQysSignature);
                        conn.setRequestProperty("x-qys-accesstoken", Apply_Token);

                        //以Post方式提交表单，默认get方式
                        conn.setRequestMethod("GET");
                        conn.setDoInput(true);
                        conn.setDoOutput(true);
                        //post方式不能使用缓存
                        conn.setUseCaches(false);
                        //连接指定的资源
                        conn.connect();
                        //获取网络输入流
                        inputStream = conn.getInputStream();
                        BufferedInputStream bis = new BufferedInputStream(inputStream);
                        //endregion


                        //region 写入到文件（注意文件保存路径的后面一定要加上文件的名称）
                        Calendar calendar = Calendar.getInstance();

                        String relativePath = "WORKFLOW_BUSINESS_COMMON" + File.separator + calendar.get(Calendar.YEAR) + (calendar.get(Calendar.MONTH) + 1) + calendar.get(Calendar.DATE);

                        String filePath = profile + File.separator + relativePath;

                        String fileName = UUID.randomUUID().toString();

                        String saveFilePath = filePath + File.separator + fileName;

                        //如果保存的目录不存在，则创建
                        File uploadFolder = new File(filePath);
                        if (!uploadFolder.exists()) {
                            uploadFolder.mkdirs();
                        }

                        fileOut = new FileOutputStream(saveFilePath + ".ofd");
                        BufferedOutputStream bos = new BufferedOutputStream(fileOut);

                        byte[] buf = new byte[4096];
                        int length = bis.read(buf);
                        //保存文件
                        while (length != -1) {
                            bos.write(buf, 0, length);
                            length = bis.read(buf);
                        }
                        bos.close();
                        bis.close();
                        conn.disconnect();
                        //endregion


                        //region 将ofd转换为pdf

//                        // 1. 文件输入路径
//                        Path src = Paths.get(saveFilePath + ".ofd");
//
//                        // 2. 加载指定目录字体(非必须)
//                        FontLoader.getInstance().scanFontDir(new File("/usr/share/fonts/zh_CN"));
//
//                        // 2. 转换后文件输出位置
//                        Path dst = Paths.get(saveFilePath + ".pdf");
//                        try {
//                            // 3. OFD转换PDF
//                            ConvertHelper.toPdf(src, dst);
//                            System.out.println("生成文档位置: " + dst.toAbsolutePath());
//                        } catch (GeneralConvertException e) {
//                            // GeneralConvertException 类型错误表明转换过程中发生异常
//                            e.printStackTrace();
//                        }

                        //endregion


                        //获取文件大小
                        File fileNew = new File(saveFilePath + ".ofd");


                        //region 加载附件标题
                        String attachName = "";

                        try {
                            var attachInfo = commonAttachmentService.queryMainAttachment(swwSignatureLog.getCommonId());
                            if (attachInfo != null) {
                                attachName = attachInfo.getName();
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        } finally {
                            if (attachName == null || StringUtils.isEmpty(attachName) || "".equals(attachName)) {
                                attachName = "已签章查阅件";
                            }
                        }
                        //endregion


                        //region 保存到数据库
                        String attchmentId = UUID.randomUUID().toString();
                        CommonAttachment attachment = new CommonAttachment();
                        attachment.setId(attchmentId);
                        attachment.setRefTableID(refTableId);
                        attachment.setRefTableName("WORKFLOW_BUSINESS_COMMON");
                        attachment.setDisplayName(attachName + ".ofd");
                        attachment.setName(attachName);
                        attachment.setExtension(".ofd");
                        attachment.setContentType("application/ofd");
                        attachment.setLength(fileNew.length());
                        attachment.setPersistentType(0);
                        attachment.setRelativePath(relativePath);
                        attachment.setInternalName(fileName + ".ofd");
                        attachment.setCreateTime(new Date());
                        attachment.setUpdateTime(new Date());
                        attachment.setSequence(0);
                        attachment.setIsDelete(0);

                        commonAttachmentService.insert(attachment);
                        //endregion


                        //回写log表
                        swwSignatureLog.setSignatrueAttachmentId(attchmentId);
                        swwSignatureService.update(swwSignatureLog);

                    } catch (Exception e) {
                        e.printStackTrace();
                        System.out.println("抛出异常！！");
                    }

                    //endregion
                }
            }
            //endregion


            return success(swwSignatureLog);
        } catch (Exception e) {
            e.printStackTrace();
            //return fail(e.getMessage());
            return fail("获取签章状态失败");
            //return success(false);
        }
    }
    //endregion


    //region 查询签章状态 V2
    @PostMapping("/getSignatureStatus2")
    @ResponseBody
    public JsonResultMessage getSignatureStatus2(@RequestBody Map<String, Object> data) {
        try {
            if (data.get("refTableId") == null) {
                throw new Exception("关系id未能获取");
            }

            String refTableId = data.get("refTableId").toString();


            //region 查询数据库，是否存在该签章
            var swwSignatureLog = swwSignatureService.selSignLogInfoByCommonId(refTableId);
            if (swwSignatureLog != null) {
                //如果没有下载最新签名后的文档，则下载
                if (swwSignatureLog.getSignatrueAttachmentId() == null || StringUtils.isEmpty(swwSignatureLog.getSignatrueAttachmentId())) {

                    //region 下载签名后的文档
                    String url = Apply_CA_URL + "document/download?documentId=" + swwSignatureLog.getDocumentId();

                    FileOutputStream fileOut = null;
                    HttpURLConnection conn = null;
                    InputStream inputStream = null;


                    //时间戳
                    String xQysTimestamp = Util.getTimeStamp();
                    //MD5加密前签名
                    String signature = Apply_Token + "" + Apply_Secret + "" + xQysTimestamp;
                    //System.out.println(signature);
                    //MD5加密后签名
                    String xQysSignature = DigestUtils.md5DigestAsHex(signature.getBytes(StandardCharsets.UTF_8));
                    //System.out.println(xQysSignature);


                    try {
                        //region 获得下载流
                        // 建立链接
                        URL httpUrl = new URL(url);
                        conn = (HttpURLConnection) httpUrl.openConnection();

                        conn.setRequestProperty("x-qys-timestamp", xQysTimestamp);
                        conn.setRequestProperty("x-qys-signature", xQysSignature);
                        conn.setRequestProperty("x-qys-accesstoken", Apply_Token);

                        //以Post方式提交表单，默认get方式
                        conn.setRequestMethod("GET");
                        conn.setDoInput(true);
                        conn.setDoOutput(true);
                        //post方式不能使用缓存
                        conn.setUseCaches(false);
                        //连接指定的资源
                        conn.connect();
                        //获取网络输入流
                        inputStream = conn.getInputStream();
                        BufferedInputStream bis = new BufferedInputStream(inputStream);
                        //endregion


                        //region 写入到文件（注意文件保存路径的后面一定要加上文件的名称）
                        Calendar calendar = Calendar.getInstance();

                        String relativePath = "WORKFLOW_BUSINESS_COMMON" + File.separator + calendar.get(Calendar.YEAR) + (calendar.get(Calendar.MONTH) + 1) + calendar.get(Calendar.DATE);

                        String filePath = profile + File.separator + relativePath;

                        String fileName = UUID.randomUUID().toString();

                        String saveFilePath = filePath + File.separator + fileName;

                        //如果保存的目录不存在，则创建
                        File uploadFolder = new File(filePath);
                        if (!uploadFolder.exists()) {
                            uploadFolder.mkdirs();
                        }

                        fileOut = new FileOutputStream(saveFilePath + ".ofd");
                        BufferedOutputStream bos = new BufferedOutputStream(fileOut);

                        byte[] buf = new byte[4096];
                        int length = bis.read(buf);
                        //保存文件
                        while (length != -1) {
                            bos.write(buf, 0, length);
                            length = bis.read(buf);
                        }
                        bos.close();
                        bis.close();
                        conn.disconnect();
                        //endregion


                        //region 将ofd转换为pdf

                        //Thread.sleep(10000);


                        // 1. 文件输入路径
                        //Path src = Paths.get(saveFilePath + ".ofd");

                        // 2. 转换后文件输出位置
                        //Path dst = Paths.get(saveFilePath + ".pdf");

                        // 3. 转换文档
//                        String fileConvertAddress = "http://10.220.251.13:6888/convert-issuer/";
//
////                        String fileNameInserverNew = uploadFilePath.substring(0, uploadFilePath.lastIndexOf(".")) + ".ofd";
////                        String fileNameNew = uploadFileName.substring(0, uploadFileName.lastIndexOf(".")) + ".ofd";
//                        HTTPAgent httpAgent = new HTTPAgent(fileConvertAddress);
//                        try {
//                            File fromFile = new File(saveFilePath + ".ofd");
//
//
//                            httpAgent.OFDToPDF(fromFile, new FileOutputStream(saveFilePath + ".pdf"));
////                            uploadFileName = fileNameNew;
////                            uploadFilePath = fileNameInserverNew;
////                            uploadFileExtension = "ofd";
//                        } catch (Exception e) {
//                            e.printStackTrace();
//                        } finally {
//
////                            Thread.sleep(5000);
//
//                            try {
//                                httpAgent.close();
//                            } catch (IOException e) {
//                                e.printStackTrace();
//                            }
//                        }

                        //endregion


                        //获取文件大小
                        File fileNew = new File(saveFilePath + ".pdf");


                        //region 加载附件标题
                        String attachName = "";

                        try {
                            var attachInfo = commonAttachmentService.queryMainAttachment(swwSignatureLog.getCommonId());
                            if (attachInfo != null) {
                                attachName = attachInfo.getName();
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        } finally {
                            if (attachName == null || StringUtils.isEmpty(attachName) || "".equals(attachName)) {
                                attachName = "已签章查阅件";
                            }
                        }
                        //endregion


                        //region 保存到数据库
                        String attchmentId = UUID.randomUUID().toString();
                        CommonAttachment attachment = new CommonAttachment();
                        attachment.setId(attchmentId);
                        attachment.setRefTableID(refTableId);
                        attachment.setRefTableName("WORKFLOW_BUSINESS_COMMON");
                        attachment.setDisplayName(attachName + ".pdf");
                        attachment.setName(attachName);
                        attachment.setExtension(".pdf");
                        attachment.setContentType("application/pdf");
                        attachment.setLength(fileNew.length());
                        attachment.setPersistentType(0);
                        attachment.setRelativePath(relativePath);
                        attachment.setInternalName(fileName + ".pdf");
                        attachment.setCreateTime(new Date());
                        attachment.setUpdateTime(new Date());
                        attachment.setSequence(0);
                        attachment.setIsDelete(0);


                        commonAttachmentService.insert(attachment);
                        //endregion


                        //回写log表
                        swwSignatureLog.setSignatrueAttachmentId(attchmentId);
                        swwSignatureService.update(swwSignatureLog);

                    } catch (Exception e) {
                        e.printStackTrace();
                        System.out.println("抛出异常！！");
                    }

                    //endregion
                }
            }
            //endregion


            return success(swwSignatureLog);
        } catch (Exception e) {
            e.printStackTrace();
            //return fail(e.getMessage());
            return fail("获取签章状态失败");
            //return success(false);
        }
    }
    //endregion


    //region 签章预览
    @PostMapping("/viewSignature")
    @ResponseBody
    public JsonResultMessage viewSignature(@RequestBody Map<String, Object> data) {
        try {
            if (data.get("refTableId") == null) {
                throw new Exception("关系id未能获取");
            }

            String attachmentId = "";

            String refTableId = data.get("refTableId").toString();

            //region 查询数据库，是否存在该签章附件
            CommonAttachment query = new CommonAttachment();
            query.setRefTableID(refTableId);
            query.setRefTableName("WORKFLOW_BUSINESS_COMMON");

            var attachments = commonAttachmentService.query(query);
            if (attachments != null && attachments.size() > 0) {
                attachmentId = attachments.get(0).getId();
            }
            //endregion

            Map<String, Object> map = new HashMap<>();
            map.put("attachmentId", attachmentId);

            return success(map);
        } catch (Exception e) {
            e.printStackTrace();
            //return fail(e.getMessage());
            return fail("签章预览失败");
            //return success(false);
        }
    }
    //endregion


    /**
     * @Description: 创建印章页面签署
     * @Author zq
     * @Version 1.0
     * @Date 2021/12/13 17:35
     */
    @PostMapping("/createSignature")
    @ResponseBody
    public JsonResultMessage createSignature(@RequestBody Map<String, Object> data) throws IOException {
        // 指定允许其他域名访问
        //response.setHeader("Access-Control-Allow-Origin","*");
        // 响应类型
        //response.setHeader("Access-Control-Allow-Methods","POST");
        // 响应头设置
        //response.setHeader("Access-Control-Allow-Headers","x-requested-with,content-type");
        UUIDGenerator uuid = new UUIDGenerator();

        Map<String, Object> resultParam = new HashMap<>();

        if (StringUtils.isEmpty(data.get("refTableId"))) {
            resultParam.put("code", "-1");
            return success("未获取到标识", resultParam);
        }

        String commonId = data.get("refTableId").toString();

        System.out.println("refTableId[]=====" + data.get("refTableId"));

        String url = Apply_CA_URL + "" + Apply_Seal_Address;

        List<EntityFileInfo> fileInfoList = swwSignatureService.selFileInfoByRefTableId(commonId);
        if (fileInfoList.size() > 0) {

            String absolutePath = profile + fileInfoList.get(0).getRelativePath() + "/" + fileInfoList.get(0).getInternalName();
            System.out.println("absolutePath[]===" + absolutePath);

            File file = new File(absolutePath);

            JSONObject jsonObj = sealTest(url, file);

            String message = "";

            if (jsonObj.getString("code").equals("0")) {
                EntitySignatureLog signatureLog = new EntitySignatureLog();
                signatureLog.setId(uuid.newId());
                signatureLog.setCommonId(commonId);
                signatureLog.setDocumentId(jsonObj.getString("documentId"));
                signatureLog.setSignatrueUrl(jsonObj.getString("url"));
                signatureLog.setDateCreate(new Date());
                signatureLog.setRemark(jsonObj.toString());

                int insSignatureLogNum = swwSignatureService.insterSignatureLog(signatureLog);

                if (insSignatureLogNum == 0) {
                    resultParam.put("code", "-1");
                    message = "签章记录写入数据库失败";
                    return success(message, resultParam);
                }

                resultParam.put("insSignatureLogNum", insSignatureLogNum);
                resultParam.put("code", jsonObj.getString("code"));
                resultParam.put("documentId", jsonObj.getString("documentId"));
                resultParam.put("message", jsonObj.getString("message"));
                resultParam.put("url", jsonObj.getString("url"));
                message = "签章创建完成";

            } else {
                resultParam.put("code", jsonObj.getString("code"));
                message = "签章创建失败";
            }

            return success(message, resultParam);

        } else {
            resultParam.put("code", "-1");
            return success("未获取到可签章的文件，请确实是否已成功制文", resultParam);

        }
    }


    /**
     * @Description: 创建印章页面签署接口调用demo
     * @Author zq
     * @Version 1.0
     * @Date 2021/12/9 15:01
     */
    public JSONObject sealTest(String requestUrl, File file) {

        CloseableHttpClient httpClient = HttpClients.createDefault();
        JSONObject jsonObj = new JSONObject();
        String result = "";
        //时间戳
        String xQysTimestamp = Util.getTimeStamp();
        //MD5加密前签名
        String signature = Apply_Token + "" + Apply_Secret + "" + xQysTimestamp;
        //System.out.println(signature);
        //MD5加密后签名
        String xQysSignature = DigestUtils.md5DigestAsHex(signature.getBytes(StandardCharsets.UTF_8));
        //System.out.println(xQysSignature);

        try {
            HttpPost httpPost = new HttpPost(requestUrl);

            httpPost.setHeader("x-qys-timestamp", xQysTimestamp);//时间戳 毫秒
            httpPost.setHeader("x-qys-signature", xQysSignature);//签名，对参数进行md5运算 , 取32位小写字符串: MD5(accessToken+accessSecret+timestamp)accessToken与accessSecret分别为创建应用分配的token和secret
            httpPost.setHeader("x-qys-accesstoken", Apply_Token);//创建应用分配的token

            MultipartEntityBuilder builder = MultipartEntityBuilder.create();
            builder.setCharset(java.nio.charset.Charset.forName("UTF-8"));
            builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
            //builder.addPart("file", new FileBody(file, ContentType.APPLICATION_OCTET_STREAM));
            //builder.addTextBody("contact", phone);//联系方式，手机号，用于签署时校验身份（使用零信任签署人工确认时校验方式为确认人手机号，可不传，确认人为ukey时需要插入ukey确认签署）
            //builder.addTextBody("sealIds", sealIds);//印章ID
            builder.addTextBody("needVerify", "false");//是否通过手机号才能完成签署，默认true是需要校验身份
            builder.addBinaryBody("file", file);//PDF/OFD文档（30M限制）

            HttpEntity entity = builder.build();

            httpPost.setEntity(entity);
            HttpResponse response = httpClient.execute(httpPost);
            // 执行提交
            HttpEntity responseEntity = response.getEntity();

            if (responseEntity != null) {
                // 将响应内容转换为字符串
                result = EntityUtils.toString(responseEntity, java.nio.charset.Charset.forName("UTF-8"));

            }
            jsonObj = JSONObject.parseObject(result);
            if (jsonObj.getString("code").equals("0")) {
                System.out.println("OK========================" + jsonObj);
            } else {
                System.out.println("NO========================" + jsonObj);
            }

        } catch (Exception e) {
            Writer w = new StringWriter();
            e.printStackTrace(new PrintWriter(w));

        } finally {
            try {
                httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return jsonObj;
        }
    }


    /**
     * @Description: 下载签署后电子文档
     * @Author zq
     * @Version 1.0
     * @Date 2021/12/15 11:07
     */
    @PostMapping("/signatureDownload")
    @ResponseBody
    public JsonResultMessage signatureDownload(@RequestBody Map<String, Object> data) throws IOException {

        Map<String, String> resultParam = new HashMap<>();

        if (StringUtils.isEmpty(data.get("commonId"))) {
            resultParam.put("code", "-1");
            return success("未获取到标识", resultParam);
        }

        String commonId = data.get("commonId").toString();

        EntitySignatureLog signatureLog = swwSignatureService.selSignLogInfoByCommonId(commonId);
        if (!StringUtils.isEmpty(signatureLog)) {
            String timestamp = Util.getTimeStamp();
            //时间戳
            resultParam.put("x-qys-timestamp", timestamp);
            String signature = Apply_Token + "" + Apply_Secret + "" + timestamp;
            String xQysSignature = DigestUtils.md5DigestAsHex(signature.getBytes(StandardCharsets.UTF_8));
            //MD5加密后的签名
            resultParam.put("x-qys-signature", xQysSignature);
            //应用分配的token
            resultParam.put("x-qys-accesstoken", Apply_Token);

            resultParam.put("code", "0");
            resultParam.put("documentId", signatureLog.getDocumentId());

            return success("获取签署后电子文档成功", resultParam);

        } else {
            resultParam.put("code", "-1");
            return success("未获取到可下载签署后电子文档", resultParam);

        }
    }


    /**
     * @Description: 启动档案移交流程
     * @Author zq
     * @Version 1.0
     * @Date 2021/12/23 13:26
     */
    @PostMapping("/startTheFileTransferProcess")
    @ResponseBody
    @SneakyThrows
    public JsonResultMessage startTheFileTransferProcess(@RequestBody Map<String, Object> data) {

        Map<String, String> resultParam = new HashMap<>();

        if (StringUtils.isEmpty(data.get("relevanIds"))) {
            return success("缺少相关流程标识", resultParam);
        }
        if (StringUtils.isEmpty(data.get("userUid"))) {
            return success("缺少用户uid", resultParam);
        }
        if (StringUtils.isEmpty(data.get("title"))) {
            return success("缺少表单标题", resultParam);
        }
        if (StringUtils.isEmpty(data.get("zwId"))) {
            return success("缺少正文id", resultParam);
        }

        //根据formId获取最新版的流程ID
        String faWenFlowId = swwSignatureService.getFlowIdByFormId(FAWEN_FORM_ID);
        System.out.println("faWenFlowId[]====" + faWenFlowId);

        if (StringUtils.isEmpty(faWenFlowId)) {
            return success("为正确获取到发文流程标识", resultParam);
        }

        String relevanIds = data.get("relevanIds").toString();
        String userUid = data.get("userUid").toString();
        String title = data.get("title").toString();
        String zwId = data.get("zwId").toString();
        String describe = data.get("describe").toString();//描述

        User user = userService.selUserByUser(userUid);

        if (StringUtils.isEmpty(user)) {
            return success("未获取到用户信息", resultParam);
        }

        String userName = user.getUserName();

        //初始化表单
        JSONObject formDataJO = new JSONObject();
        formDataJO.put("TITLE", title);
        formDataJO.put("NBYJ", relevanIds);
        formDataJO.put("RELEVANT_IDS", relevanIds);
        /*formDataJO.put("CBCS", "办公室");
        formDataJO.put("FQR", "张三");*/

        formDataJO.put("FLOW_ID", faWenFlowId);
        formDataJO.put("COMMON_ID", "");
        formDataJO.put("FORM_ID", FAWEN_FORM_ID);
        formDataJO.put("FORM_TEMPLATE_ID", FAWEN_FORM_TEMPLATE_ID);
        formDataJO.put("IS_TEMP_SAVE", 0);
        formDataJO.put("TEMP_SAVE", 1);
        formDataJO.put("UNIT_CODE", "QSWW");
        formDataJO.put("UNIT_NAME", "区商务委");
        //formDataJO.put("PROC_DEF_ID", "wf_1573785108149:1:8057953");


        String addResourceResult = addResource(REST_API_PROCFORMDESIGNDATA, formDataJO);
        JSONObject newFile = JSONObject.parseObject(addResourceResult);
        String businessId = newFile.getString("data");

        if (StringUtils.isEmpty(businessId)) {
            resultParam.put("addResourceResult", addResourceResult);
            return success("流程创建异常", resultParam);
        }

        System.out.println("addResourceResult[]============" + addResourceResult);
        System.out.println("businessId[]============" + businessId);

        String orgCode = user.getOrgCode();
        String unitCode = "QSWW";

        //开启流程
        String url = REST_API_START + "?flowId=" + faWenFlowId + "&formCommonId=" + businessId + "&sourceProcessInstanceId=&nextUserUid=&nodeCode=&action=&orgCode=" + orgCode + "&userName=" + userName + "&userUid=" + userUid + "&unitCode=" + unitCode;
        System.out.println(url);
        HttpHeaders headers = new HttpHeaders();
        //headers.set("authorization","Bearer 93fb708b-7b0f-4d0e-ad6a-adbdc8f6b0bc");
        RestTemplate restTemplate = new RestTemplate();
        org.springframework.http.HttpEntity<String> ans = restTemplate.exchange(url, HttpMethod.GET, new org.springframework.http.HttpEntity<>(null, headers), String.class);  //body响应数据接收类型
        String flowStartResult = ans.getBody();
        if (StringUtils.isEmpty(flowStartResult)) {
            return success("启动异常", resultParam);
        }
        System.out.println("flowStartResult[]=============" + flowStartResult);
        JSONObject flowStartObj = JSONObject.parseObject(flowStartResult);
        String flowStartData = flowStartObj.getString("data");
        String flowStartMessage = flowStartObj.getString("message");

        if (!flowStartMessage.equals("流程启动成功！")) {
            return success("流程启动失败", resultParam);
        }

        resultParam.put("addResourceResult", addResourceResult);
        resultParam.put("flowStartResult", flowStartResult);
        resultParam.put("businessId", businessId);

        return success("流程启动成功", resultParam);
    }

    public static String addResource(String url, JSONObject object) throws Exception {
        HttpClient httpClient = new DefaultHttpClient();
        ObjectMapper mapper = new ObjectMapper();

        HttpPost request = new HttpPost(url);
        request.setHeader("Content-Type", "application/json");
        request.setHeader("Accept", "application/json");
        StringEntity requestJson = new StringEntity(mapper.writeValueAsString(object), "utf-8");
        requestJson.setContentType("application/json");
        //request.setHeader("Authorization","Bearer 93fb708b-7b0f-4d0e-ad6a-adbdc8f6b0bc");
        request.setEntity(requestJson);
        HttpResponse response = httpClient.execute(request);
        String json = EntityUtils.toString(response.getEntity());
        //System.out.print("addResource result is : " + json + "\n");
        return json;
    }


    @ResponseBody
    @RequestMapping("testA")
    @SneakyThrows
    public void processFlowStart(@RequestBody JSONObject content) {
        System.out.println("JSONObject======" + content);
        //获取表单信息；保存表单
        String userName = content.getString("userName");
        String userId = content.getString("userUid");
        JSONObject object = new JSONObject();
        object = content.getJSONObject("formDataMap");
        System.out.println("formDataMap======" + object);


        //Map<String, Object> formDataMap = new HashMap<>();
        //String formDataMapStr = JSONObject.toJSONString(formDataMap);
        //JSONObject formDataJO = JSON.parseObject(formDataMapStr);
    }
}
